/**
 *博尔信基础开发平台
 *<br> 版权声明：厦门博尔信软件有限公司版权所有,违者必究
 *<br> Copyright:  Copyright (c) 2012
 *<br> Company:pearlsoft
 *<br> @author 蒋勇华
 *<br> 2012-5-10
 *<br> @version 1.0
 *————————————————————————————————————
 *修改记录
 *    修改者：
 *    修改时间：
 *    修改原因：
 *——————————————————————————————————————
 */
package com.pearlsoft.webapp.rms.resapply.service;

import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.pearlsoft.commons.utils.UUIDUtil;
import com.pearlsoft.rms.VcloudManager;
import com.pearlsoft.util.DateUtils;
import com.pearlsoft.util.StringUtils;
import com.pearlsoft.webapp.core.WebException;
import com.pearlsoft.webapp.core.dao.RecrodRowMapper;
import com.pearlsoft.webapp.core.dataset.Record;
import com.pearlsoft.webapp.core.dataset.SimpleRecord;
import com.pearlsoft.webapp.core.service.BaseSimpleJdbcService;
import com.pearlsoft.webapp.rms.StepStatus;
import com.vmware.vcloud.sdk.Vapp;
import com.vmware.vcloud.sdk.Vdc;

/**
 * 描述： 资源申请服务
 * 
 * 
 */
@Service
public class ResApplyService extends BaseSimpleJdbcService {

    private final String generalFields = " {0}.stepId, {0}.flowId, {0}.authorId, {0}.stepName,{0}.stepType,{0}.startTime,{0}.endTime,{0}.opinion,{0}.stepstatus,"
            + "{1}.applyId,{1}.resName,{1}.resDesc,{1}.startDate,{1}.endDate ";
    private final RecrodRowMapper generalRowMapper = ResApplyRowMapperHelper.generalRowMapper();
    private final RecrodRowMapper resApplyRowMapper = ResApplyRowMapperHelper.resApplyRowMapper();
    private final RecrodRowMapper hostConfigRowMapper = ResApplyRowMapperHelper.hostConfigRowMapper();
    private final RecrodRowMapper auditLogRowMapper = ResApplyRowMapperHelper.auditLogRowMapper();

    @Autowired
    private VcloudManager vcloudManager;

    protected VcloudManager getVcloudManager() {
        return this.vcloudManager;
    }

    public Record getById(String applyId) {
        String sql = " select r.applyId,r.resName,r.resDesc,r.startDate,r.endDate,r.authorId,u.user_name,t.endTime,r.eName "
                + "from rms_resapply r left join sys_user u on r.authorId=u.user_id "
                + "left join  rms_flowstep t  on r.applyId = t.applyId "
                + "where r.applyId=:applyId and t.stepType='0'";
        Map<String, String> param = new HashMap<String, String>();
        param.put("applyId", applyId);
        Record record = this.getBaseSimpleJdbcDao().queryOne(sql, param, resApplyRowMapper);
        if (record == null) {
            return null;
        }
        String sqlHost = "select  configId,applyId,hostName,vmName,hostDesc,opsSeries,opsName,vVersion,cups,memory,memoryunit,storage,storageunit,netcards,zxtype,hostIp ";
        sqlHost = sqlHost + " from rms_hostconfig where applyId=:applyId";
        List<Record> hostList = this.getBaseSimpleJdbcDao().query(sqlHost, param, hostConfigRowMapper);
        List<Map> tempList = new ArrayList<Map>();
        for (Record temp : hostList) {
            tempList.add(temp.toMap());
        }
        if (tempList != null && tempList.size() > 0) {
            record.setValue("hostList", tempList);
        } else {
            record.setValue("hostList", null);
        }
        return record;
    }

    public void deleteById(String applyId) {
        Map<String, String> param = new HashMap<String, String>();
        param.put("applyId", applyId);
        String sql = "delete from rms_resapply where applyId=:applyId";
        String usql = "delete from rms_hostconfig where applyId=:applyId";
        String ssql = "delete from rms_flowstep where stepType='0' and applyId=:applyId";
        this.getBaseSimpleJdbcDao().update(sql, param);
        this.getBaseSimpleJdbcDao().update(usql, param);
        this.getBaseSimpleJdbcDao().update(ssql, param);

    }

    /***
     * 得到某用户的资源申请列表
     * 
     * @param userId
     * @return
     */
    public List<Record> getApplyList(String userId) {
        String sql = " select " + StringUtils.format(generalFields, "f", "r") + " from rms_flowstep f  "
                + " left join rms_resapply r on f.applyId = r.applyId "
                + "where f.authorId=:authorId and f.stepType='0' order by f.startTime desc";
        Map<String, String> param = new HashMap<String, String>();
        param.put("authorId", userId);
        return this.getBaseSimpleJdbcDao().query(sql, param, generalRowMapper);
    }

    /***
     * 审批日志
     * 
     * @param applyId 申请对象ID
     * @return
     */
    public List<Record> getAuditLogList(String applyId) {
        String sql = "select t.stepName,u.user_name,t.endTime,t.opinion,t.result ";
        sql = sql + " from rms_flowstep t left join sys_user u on t.authorId=u.user_id  ";
        sql = sql + "where t.applyId=:applyId and t.stepstatus=:stepstatus order by t.stepType ";
        Map<String, String> param = new HashMap<String, String>();
        param.put("applyId", applyId);
        param.put("stepstatus", StepStatus.DEALED);
        return this.getBaseSimpleJdbcDao().query(sql, param, auditLogRowMapper);
    }

    /***
     * 保存或者更新申请单
     * 
     * @param record
     * @throws WebException
     */
    public void save(Record record) throws WebException {
        String objId = (String) record.getValue("applyId");
        if (StringUtils.isBlank(objId)) {
            this.insertRecord(record);
            this.saveNewStep1(record);
        } else {
            this.updateRecord(record);
        }
    }

    /**
     * 新建资源申请步骤
     * 
     * @param record
     * @throws WebException
     */
    private void saveNewStep1(Record record) throws WebException {
        String stepId = UUIDUtil.get();
        String flowId = UUIDUtil.get();
        String applyId = (String) record.getValue("applyId");
        String authorId = (String) record.getValue("authorId");

        String sql = "insert into rms_flowstep(stepId,flowId,applyId,authorId,stepName,stepType,startTime,stepstatus,hasdeal)";
        sql = sql + "values( :stepId,:flowId,:applyId,:authorId,:stepName,:stepType,:startTime,:stepstatus,:hasdeal)";
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("stepId", stepId);
        param.put("flowId", flowId);
        param.put("applyId", applyId);
        param.put("authorId", authorId);
        param.put("stepName", "资源申请");
        param.put("stepType", "0");
        param.put("startTime", DateUtils.getCurrentDate());
        param.put("stepstatus", StepStatus.NEWSTEP);
        param.put("hasdeal", "0");
        this.getBaseSimpleJdbcDao().update(sql, param);
    }

    /***
     * 资源配置审批步骤
     * 
     * @param record
     * @throws WebException
     */
    private void saveNewStep2(Record record) throws WebException {
        String stepId = UUIDUtil.get();
        String applyId = (String) record.getValue("applyId");
        String flowId = this.getFlowId(applyId);
        String authorId = this.getAuthorId("1");
        String sql = "insert into rms_flowstep(stepId,flowId,applyId,authorId,stepName,stepType,startTime,stepstatus,hasdeal)";
        sql = sql + "values( :stepId,:flowId,:applyId,:authorId,:stepName,:stepType,:startTime,:stepstatus,:hasdeal)";
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("stepId", stepId);
        param.put("flowId", flowId);
        param.put("applyId", applyId);
        param.put("authorId", authorId);
        param.put("stepName", "资源配置审批");
        param.put("stepType", "1");
        param.put("startTime", DateUtils.getCurrentDate());
        param.put("stepstatus", StepStatus.UNDEAL);
        param.put("hasdeal", "0");
        this.getBaseSimpleJdbcDao().update(sql, param);
    }

    private String getFlowId(String applyId) {
        String sql = " select flowId from rms_flowstep t where t.applyId=:applyId and t.stepType='0'";
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("applyId", applyId);
        List<Record> list = this.getBaseSimpleJdbcDao().query(sql, param, new RecrodRowMapper<Record>() {
            @Override
            public Record mapRow(ResultSet rs, int rowNum) throws SQLException {
                SimpleRecord recrod = new SimpleRecord();
                recrod.setValue("flowId", rs.getString(1));
                return recrod;
            }
        });
        Record record = list.get(0);
        return (String) record.getValue("flowId");
    }

    /**
     * 根据步骤类型获取可以处理该步骤类型的人员
     * 
     * @param stepType
     * @return
     */
    private String getAuthorId(String stepType) {
        String roleName = "";
        if (stepType.equalsIgnoreCase("0")) {
            roleName = "申请岗";
        } else if (stepType.equalsIgnoreCase("1")) {
            roleName = "资源管理岗";
        } else if (stepType.equalsIgnoreCase("2")) {
            roleName = "中心领导";
        } else if (stepType.equalsIgnoreCase("3")) {
            roleName = "资源管理岗";
        }
        String sql = "select t.USER_ID from sys_user_role  t left join sys_role r on t.ROLE_ID = r.ROLE_ID ";
        sql = sql + " where r.ROLE_NAME =:ROLE_NAME";
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("ROLE_NAME", roleName);
        List<Record> list = this.getBaseSimpleJdbcDao().query(sql, param, new RecrodRowMapper<Record>() {
            @Override
            public Record mapRow(ResultSet rs, int rowNum) throws SQLException {
                SimpleRecord recrod = new SimpleRecord();
                recrod.setValue("USER_ID", rs.getString(1));
                return recrod;
            }
        });
        Record record = list.get(0);
        return (String) record.getValue("USER_ID");
    }

    /***
     * 执行提交申请操作
     * 
     * @param record
     * @throws WebException
     */
    public void apply(Record record) throws Exception {
        int checkRes = this.checkRes(record);
        if (checkRes > 0) {
            // 保存或者更新申请单
            this.save(record);
            String applyId = (String) record.getValue("applyId");
            // 更新步骤状态
            String sql = " update rms_flowstep  set stepstatus=:stepstatus, endTime=:endTime where applyId=:applyId and stepType='0' ";
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("applyId", applyId);
            param.put("stepstatus", StepStatus.WAITAUDIT);
            param.put("endTime", DateUtils.getCurrentDate());
            this.getBaseSimpleJdbcDao().update(sql, param);
            // 自动生成下一步骤
            this.saveNewStep2(record);
            record.setValue("applystatus", "1");
            record.setValue("applyError", "");

        } else {
            record.setValue("applystatus", "0");
            if (checkRes == -2) {
                record.setValue("applyError", "在您申请的时间段,服务器内存和硬盘不足,\r\n请修改内存和硬盘大小或项目调整时间");
            } else if (checkRes == -1) {
                record.setValue("applyError", "在您申请的时间段,服务器硬盘不足,\r\n请修改硬盘大小或调整项目时间");
            } else if (checkRes == -0) {
                record.setValue("applyError", "在您申请的时间段,服务器内存不足,\r\n请修改内存大小或调整项目时间");
            }
        }
    }

    /***
     * 资源检查
     * @param record
     * @return 1:正常,0:内存不足,-1:硬盘不足,-2:内存和硬盘都不足
     * @throws Exception
     */
    private int checkRes(Record record) throws Exception {
        int ret = 1;
        String startDate = (String) record.getValue("startDate");
        String endDate = (String) record.getValue("endDate");
        ArrayList<Map> hostList = (ArrayList<Map>) record.getValue("hostList");
        int totalApplyCpus = 0, totalApplyMem = 0, totalApplyDiskHard = 0;
        for (Map hostMap : hostList) {
            int applyCpus = Integer.parseInt((String) hostMap.get("cups"));
            int applyMem = Integer.parseInt((String) hostMap.get("memory"));
            int applyDisk = Integer.parseInt((String) hostMap.get("storage"));
            String munit = (String) hostMap.get("memoryunit");
            String dunit = (String) hostMap.get("storageunit");
            if ("1".equalsIgnoreCase(munit)) {
                applyMem = applyMem * 1024;
            }
            if ("1".equalsIgnoreCase(dunit)) {
                applyDisk = applyDisk * 1024;
            }
            if ("2".equalsIgnoreCase(dunit)) {
                applyDisk = applyDisk * 1024 * 1024;
            }
            totalApplyCpus = totalApplyCpus + applyCpus;
            totalApplyMem = totalApplyMem + applyMem;
            totalApplyDiskHard = totalApplyDiskHard + applyDisk;
        }

        Map map = this.getVcloudManager().getVdcResource("test", "test");
        int totalCpu = Integer.parseInt((String) map.get("cpu"));
        int totalMem = Integer.parseInt((String) map.get("mem"));
        int totalDisk = Integer.parseInt((String) map.get("disk"));

        Vdc vdc = this.getVcloudManager().findVdc("test", "test");
        Map<String, Integer> runTimeMap = this.getRuntimeResource(vdc, startDate, endDate);
        boolean checkMem = true;
        boolean checkDisk = true;
        if ((totalApplyMem + runTimeMap.get("mem")) > totalMem * 1) {
            checkMem = false;
        }
        if ((totalApplyDiskHard + runTimeMap.get("disk")) > (totalDisk * 0.8)) {
            checkDisk = false;
        }
        if (checkMem == false && checkDisk == false) {
            ret = -2;
        } else if (checkMem == true && checkDisk == false) {
            ret = -1;
        } else if (checkMem == false && checkDisk == true) {
            ret = 0;
        } else {
            ret = 1;
        }
        return ret;
    }

    private Map<String, Integer> getRuntimeResource(Vdc vdc, String startDate, String endDate) throws Exception {
        String sql = "SELECT A.startDate,A.endDate,a.resId AS resId,A.resName,A.eName,SUM(B.cups)AS cpus,SUM(B.memory)AS 'memory' ,B.memoryunit AS memoryunit ,SUM(B.storage)AS 'storage' ,B.storageunit AS storageunit ,SUM(B.netcards)AS netcards "
                + "FROM rms_myres A"
                + " LEFT JOIN rms_myhost B "
                + "ON a.resId = B.resId "
                + "WHERE (startDate >=? AND startDate<=?)"
                + " OR(endDate >=? AND endDate<=?)"
                + " OR (startDate <=? AND endDate>=?) " + "OR (startDate >=? AND endDate<=?)" + "GROUP BY A.resId  ";
        Map<String, Integer> resources = new HashMap<String, Integer>();
        JdbcTemplate template = this.getBaseSimpleJdbcDao().getJdbcTemplate();
        List<Map<String, Object>> result = (List<Map<String, Object>>) template.queryForList(sql, new Object[] {
                startDate, endDate, startDate, endDate, startDate, endDate, startDate, endDate });

        Date start = new SimpleDateFormat("yyyy-MM-dd").parse(startDate);
        Date end = new SimpleDateFormat("yyyy-MM-dd").parse(endDate);
        Calendar calStart = Calendar.getInstance();
        calStart.setTime(start);
        Calendar calEnd = Calendar.getInstance();
        calEnd.setTime(end);
        long ms = calEnd.getTimeInMillis() - calStart.getTimeInMillis();
        long days = ms / (1000 * 3600 * 24);
        int maxCpu = 0, maxMem = 0, maxDisk = 0;
        Map<String, Vapp> vapps = vcloudManager.getVappMap(vdc);
        for (int i = 0; i <= days; i++) {
            int totalCpu = 0, totalMem = 0, totalDisk = 0;
            for (Map<String, Object> record : result) {
                java.sql.Date sdate = (java.sql.Date) record.get("startDate");
                java.sql.Date edate = (java.sql.Date) record.get("endDate");
                if (calStart.getTimeInMillis() < edate.getTime() && calStart.getTimeInMillis() > sdate.getTime()) {

                    BigDecimal cpu = (BigDecimal) record.get("cpus");
                    BigDecimal memory = (BigDecimal) record.get("memory");
                    String memUnit = (String) record.get("memoryunit");
                    if ("1".equals(memUnit)) {
                        memory = memory.multiply(new BigDecimal("1024"));
                    }
                    Vapp vapp = vapps.get((String) record.get("eName"));
                    BigDecimal storage = new BigDecimal(vapp.getVappSize());
                    totalCpu += cpu.intValue();
                    totalMem += memory.intValue();
                    totalDisk += storage.intValue();
                    if (totalCpu > maxCpu) {
                        maxCpu = totalCpu;
                    }
                    if (totalMem > maxMem) {
                        maxMem = totalMem;
                    }
                    if (totalDisk > maxDisk) {
                        maxDisk = totalDisk;
                    }
                }
            }
            calStart.add(Calendar.DATE, 1);
        }
        resources.put("mem", maxMem);
        resources.put("cpu", maxCpu);
        resources.put("disk", maxDisk);
        return resources;
    }

    public List<Map<String, Object>> getRuntimeResource(String startDate, String endDate) throws Exception {
        String sql = "SELECT A.startDate,A.endDate,a.resId AS resId,A.resName,A.eName,SUM(B.cups)AS cpus,SUM(B.memory)AS 'memory' ,B.memoryunit AS memoryunit ,SUM(B.storage)AS 'storage' ,B.storageunit AS storageunit ,SUM(B.netcards)AS netcards "
                + "FROM rms_myres A"
                + " LEFT JOIN rms_myhost B "
                + "ON a.resId = B.resId "
                + "WHERE (startDate >=? AND startDate<=?)"
                + " OR(endDate >=? AND endDate<=?)"
                + " OR (startDate <=? AND endDate>=?) " + "OR (startDate >=? AND endDate<=?)" + "GROUP BY A.resId  ";
        List<Map<String, Object>> resources = new ArrayList<Map<String, Object>>();
        JdbcTemplate template = this.getBaseSimpleJdbcDao().getJdbcTemplate();
        List<Map<String, Object>> result = (List<Map<String, Object>>) template.queryForList(sql, new Object[] {
                startDate, endDate, startDate, endDate, startDate, endDate, startDate, endDate });

        Date start = new SimpleDateFormat("yyyy-MM-dd").parse(startDate);
        Date end = new SimpleDateFormat("yyyy-MM-dd").parse(endDate);
        Calendar calStart = Calendar.getInstance();
        calStart.setTime(start);
        Calendar calEnd = Calendar.getInstance();
        calEnd.setTime(end);
        long ms = calEnd.getTimeInMillis() - calStart.getTimeInMillis();
        long days = ms / (1000 * 3600 * 24);
        Map<String, Vapp> vapps = vcloudManager.getVappMap(vcloudManager.findVdc("test", "test"));
        for (int i = 0; i <= days; i++) {
            Map<String, Object> dayResources = new HashMap<String, Object>();
            int totalCpu = 0, totalMem = 0, totalDisk = 0;
            for (Map<String, Object> record : result) {
                java.sql.Date sdate = (java.sql.Date) record.get("startDate");
                java.sql.Date edate = (java.sql.Date) record.get("endDate");
                if (calStart.getTimeInMillis() < edate.getTime() && calStart.getTimeInMillis() > sdate.getTime()) {

                    BigDecimal cpu = (BigDecimal) record.get("cpus");
                    BigDecimal memory = (BigDecimal) record.get("memory");
                    String memUnit = (String) record.get("memoryunit");
                    if ("1".equals(memUnit)) {
                        memory = memory.multiply(new BigDecimal("1024"));
                    }
                    Vapp vapp = vapps.get((String) record.get("eName"));
                    BigDecimal storage = new BigDecimal(vapp.getVappSize());
                    totalCpu += cpu.intValue();
                    totalMem += memory.intValue();
                    totalDisk += storage.intValue();
                }
            }
            dayResources.put("date", new SimpleDateFormat("yyyy-MM-dd").format(calStart.getTime()));
            dayResources.put("cpu", totalCpu);
            dayResources.put("mem", totalMem);
            dayResources.put("disk", totalDisk);
            resources.add(dayResources);
            calStart.add(Calendar.DATE, 1);
        }
        return resources;
    }

    private void insertRecord(Record record) {
        String id = UUIDUtil.get();
        record.setValue("applyId", id);

        String sql = "insert into rms_resapply(applyId,resName,eName,resDesc,startDate,endDate,authorId) "
                + " values(:applyId,:resName,:eName,:resDesc,:startDate,:endDate,:authorId)";
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("applyId", (String) record.getValue("applyId"));
        param.put("resName", (String) record.getValue("resName"));
        param.put("eName", (String) record.getValue("eName"));
        param.put("resDesc", (String) record.getValue("resDesc"));

        try {
            param.put("startDate", DateUtils.getDate((String) record.getValue("startDate"), "yyyy-MM-dd"));
            param.put("endDate", DateUtils.getDate((String) record.getValue("endDate"), "yyyy-MM-dd"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        param.put("authorId", (String) record.getValue("authorId"));

        this.getBaseSimpleJdbcDao().update(sql, param);

        String hostsql = "insert into rms_hostconfig( configId,applyId,hostDesc,opsSeries,"
                + "opsName,vVersion,cups,memory,memoryunit,storage,storageunit,netcards,zxtype)";
        hostsql = hostsql
                + "values(:configId,:applyId,:hostDesc,:opsSeries,:opsName,:vVersion,:cups,:memory,:memoryunit,:storage,:storageunit,:netcards,:zxtype)";
        ArrayList<Map> hostList = (ArrayList<Map>) record.getValue("hostList");
        for (Map hostMap : hostList) {
            // :configId,:applyId,:hostName,:vmName,:hostDesc,:opsSeries,:opsName,:vVersion,:cups,
            // :memory,:memoryunit,:storage,:storageunit,:netcards,:zxtype
            Map<String, Object> hostparam = new HashMap<String, Object>();
            String hostId = UUIDUtil.get();
            hostMap.put("configId", hostId);
            hostMap.put("applyId", id);
            hostparam.put("configId", hostId);
            hostparam.put("applyId", id);
            // hostparam.put("hostName", (String)hostMap.get("hostName"));
            // hostparam.put("vmName", (String)hostMap.get("vmName"));
            hostparam.put("hostDesc", (String) hostMap.get("hostDesc"));
            hostparam.put("opsSeries", (String) hostMap.get("opsSeries"));
            hostparam.put("opsName", (String) hostMap.get("opsName"));
            hostparam.put("vVersion", (String) hostMap.get("vVersion"));
            hostparam.put("cups", Integer.parseInt((String) hostMap.get("cups")));
            hostparam.put("memory", Integer.parseInt((String) hostMap.get("memory")));
            hostparam.put("memoryunit", (String) hostMap.get("memoryunit"));
            hostparam.put("storage", Integer.parseInt((String) hostMap.get("storage")));
            hostparam.put("storageunit", (String) hostMap.get("storageunit"));
            hostparam.put("netcards", Integer.parseInt((String) hostMap.get("netcards")));
            hostparam.put("zxtype", (String) hostMap.get("zxtype"));
            this.getBaseSimpleJdbcDao().update(hostsql, hostparam);
        }

    }

    private void updateRecord(Record record) {
        String sqldel = "delete from rms_hostconfig where applyId=:applyId";
        Map<String, String> delParam = new HashMap<String, String>();
        delParam.put("applyId", (String) record.getValue("applyId"));
        this.getBaseSimpleJdbcDao().update(sqldel, delParam);

        String sql = "update rms_resapply set resName=:resName,eName=:eName,resDesc=:resDesc,startDate=:startDate,endDate=:endDate where applyId=:applyId";
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("resName", (String) record.getValue("resName"));
        param.put("eName", (String) record.getValue("eName"));
        param.put("resDesc", (String) record.getValue("resDesc"));
        try {
            param.put("startDate", DateUtils.getDate((String) record.getValue("startDate"), "yyyy-MM-dd"));
            param.put("endDate", DateUtils.getDate((String) record.getValue("endDate"), "yyyy-MM-dd"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        param.put("applyId", (String) record.getValue("applyId"));
        this.getBaseSimpleJdbcDao().update(sql, param);

        String hostsql = "insert into rms_hostconfig( configId,applyId,hostDesc,opsSeries,"
                + "opsName,vVersion,cups,memory,memoryunit,storage,storageunit,netcards,zxtype)";
        hostsql = hostsql
                + "values(:configId,:applyId,:hostDesc,:opsSeries,:opsName,:vVersion,:cups,:memory,:memoryunit,:storage,:storageunit,:netcards,:zxtype)";
        ArrayList<Map> hostList = (ArrayList<Map>) record.getValue("hostList");

        for (Map hostMap : hostList) {
            Map<String, Object> hostparam = new HashMap<String, Object>();
            String hostId = UUIDUtil.get();
            hostMap.put("configId", hostId);
            hostMap.put("applyId", (String) record.getValue("applyId"));

            hostparam.put("configId", hostId);
            hostparam.put("applyId", (String) record.getValue("applyId"));
            // hostparam.put("hostName", (String)hostMap.get("hostName"));
            // hostparam.put("vmName", (String)hostMap.get("vmName"));
            hostparam.put("hostDesc", (String) hostMap.get("hostDesc"));
            hostparam.put("opsSeries", (String) hostMap.get("opsSeries"));
            hostparam.put("opsName", (String) hostMap.get("opsName"));
            hostparam.put("vVersion", (String) hostMap.get("vVersion"));
            hostparam.put("cups", Integer.parseInt((String) hostMap.get("cups")));
            hostparam.put("memory", Integer.parseInt((String) hostMap.get("memory")));
            hostparam.put("memoryunit", (String) hostMap.get("memoryunit"));
            hostparam.put("storage", Integer.parseInt((String) hostMap.get("storage")));
            hostparam.put("storageunit", (String) hostMap.get("storageunit"));
            hostparam.put("netcards", Integer.parseInt((String) hostMap.get("netcards")));
            hostparam.put("zxtype", (String) hostMap.get("zxtype"));
            this.getBaseSimpleJdbcDao().update(hostsql, hostparam);
        }
    }

    public static void main(String[] args) throws Throwable {
        ApplicationContext context = new ClassPathXmlApplicationContext(
                new String[] { "classpath:applicationContext*.xml" });
        ResApplyService service = context.getBean("resApplyService", ResApplyService.class);
        Vdc vdc = service.vcloudManager.findVdc("test", "test");
        Map<String, Integer> max = service.getRuntimeResource(vdc, "2012-05-01", "2012-06-01");
        List<Map<String, Object>> data = service.getRuntimeResource("2012-05-24", "2012-06-01");
        System.out.println(max);
        System.out.println(data);
    }

}
